package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.sosee.cgfw.entity.User;
import com.sosee.cgfw.R;
import com.sosee.cgfw.friends.SharedPreferencesUtils;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.notification.PushNotificationMessage;

/**
 * Created by Thinkpad on 2016/3/1.
 * 登陆界面
 */
public class LoginActivity extends Activity {
    private EditText tv_username;
    private EditText tv_password;
    private HttpUtils httpUtils;
    private String userName;
    private String password;
    private int flag;//判断登陆成功后需要跳转到什么界面
    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view=inflater.inflate(R.layout.activity_login, null);
        initView();
        initData();



    }


    public void initView(){
        tv_username= (EditText) findViewById(R.id.tv_username);
        tv_password= (EditText) findViewById(R.id.tv_password);
    }

    public void initData(){
        httpUtils=new HttpUtils();
        flag=getIntent().getIntExtra(Constans.flag,0);
    }


    //点击事件
    public void onClick(View view){
        int id=view.getId();
        switch (id){
            //登陆
            case R.id.rl_login:
                login();
                break;
            //取消
            case R.id.rl_cancle:
                if(flag==100){
                    startActivity(new Intent(this,PersonalSettingActivity.class));
                }
                finish();
                break;
            //忘记密码
            case R.id.ig_forget:
                startActivity(new Intent(this,ForgotPassActivity.class));
                break;
            //注册
            case R.id.ig_register:
                startActivity(new Intent(this,RegisterActivity.class));
                break;
        }
    }

    private String userID;

    //登陆  获取融云所需要的token 并保存至本地 用于连接融云服务器
    public void login(){

        userName=tv_username.getText().toString();
        password=tv_password.getText().toString();
        LogUtils.log_E("username:"+userName+"===password:"+password);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.LOGIN_URL + userName + "&p=" + password, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                //如果登录成功。


                try {
                    JSONObject jsonObject=new JSONObject(responseInfo.result);
                    LogUtils.log_E("登陆json："+responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){

                        userID=jsonObject.getString("userID");
                        Constans.userID=userID;
                        Utils.showToast("登录成功");
                        requestHttp(userID);
                        //获取token
                        String token = SharedPreferencesUtils.getString(LoginActivity.this, "token");
                        connect(token);
                        getUserInfo();
                        requestHttp1();
                    }else{
                        Utils.showToast("用户名或者密码错误");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }
    //获取用户信息
    public void getUserInfo(){

        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.USER_INFO_URL + Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Constans.user= com.alibaba.fastjson.JSONObject.parseObject(responseInfo.result,User.class);
                Gson gson= new Gson();
                User user = gson.fromJson(responseInfo.result, User.class);
                String realname = user.getRealname();
                String company = user.getCompany();
                String duty = user.getDuty();

                goMain(realname, company,duty);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常"+s);

            }
        });
    }
    //获取用户的好友列表
    private void requestHttp1() {
        httpUtils.configCurrentHttpCacheExpiry(100);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.GETFRIENDSLIST_URL+Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                SharedPreferencesUtils.putString(LoginActivity.this, "dd", result);
                System.out.println("我是好友列表返回的数据：" + result);

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });    }
    //获取融云所需要的token
    private void requestHttp(String userID){

        //这里是空。
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.GETTOKEN_URL + userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                System.out.println("这是token值：" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String token = jsonObject.getString("token");
                    //吧token值存起来。
                    if (token != null) {
                        SharedPreferencesUtils.putString(LoginActivity.this, "token", token);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });


    }
    //跳转界面
    public void goMain(String realname,String company,String duty){
        LogUtils.log_E("测试用户信息："+Constans.userID+Constans.user.getPic());
       Intent intent=null;
        switch (flag){
            case Constans.PERSONALINFO:
                intent=new Intent(this,PersonalInfo.class);
                break;
            case Constans.FREND:
                //这里优先跳转首页。
                intent=new Intent(this,MainActivity.class);

                break;
            case Constans.EPASS:
                intent=new Intent(this,MyTicketActivity.class);
                break;
            case Constans.ASSISTANT:
                intent=new Intent(this,AssistantActivity.class);
                break;
            case 100:
                intent=new Intent(this,PersonalSettingActivity.class);
                break;
        }
        if(flag==Constans.DETAIL||flag==0){
            finish();
        }else{
            startActivity(intent);
            finish();
        }

    }

    PopupWindow popupWindow=null;
    public void showPopup(){
        popupWindow=new PopupWindow(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        View v=View.inflate(this,R.layout.pop_openinfo_friends,null);
        v.findViewById(R.id.tv_cancle_s).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopWindow();
            }
        });
        v.findViewById(R.id.tv_confim_s).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里打开信息界面，让其填写。
                startActivity(new Intent(LoginActivity.this,PersonalInfo.class));
                closePopWindow();
            }
        });
        popupWindow.setContentView(v);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    //关闭 pop
    public void closePopWindow(){
        if (popupWindow!=null){
            popupWindow.dismiss();
        }
    }


    //处理好友消息推送功能
    private class MyReceiveMessageListener implements RongIMClient.OnReceiveMessageListener {

        /**
         * 收到消息的处理。
         *
         * @param message 收到的消息实体。
         * @param left    剩余未拉取消息数目。
         * @return 收到消息是否处理完成，true 表示走自已的处理方式，false 走融云默认处理方式。
         */
        @Override
        public boolean onReceived(Message message, int left) {
            //开发者根据自己需求自行处理
            return false;
        }
    }

    private class MyReceivePushMessageListener implements RongIMClient.OnReceivePushMessageListener{

        /**
         * 收到 push 消息的处理。
         *
         * @param pushNotificationMessage push 消息实体。
         * @return true 自己来弹通知栏提示，false 融云 SDK 来弹通知栏提示。
         */
        @Override
        public boolean onReceivePushMessage(PushNotificationMessage pushNotificationMessage) {
            return false;
        }
    }

    private void connect(String token) {
        LogUtils.log_E("测试token"+token);

//        if (getApplicationInfo().packageName.equals(MyApplication.getCurProcessName(getApplicationContext()))) {

        /**
         *  设置接收消息的监听器。
         */
        RongIM.setOnReceiveMessageListener(new MyReceiveMessageListener());
        /**
         * 设置接收 push 消息的监听器。
         */
        RongIM.setOnReceivePushMessageListener(new MyReceivePushMessageListener());


        /**
         * IMKit SDK调用第二步,建立与服务器的连接
         */
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
             */
            @Override
            public void onTokenIncorrect() {

                LogUtils.log_E("--onTokenIncorrect");
//                    requestHttp();
            }

            /**
             * 连接融云成功
             * @param userid 当前 token
             */
            @Override
            public void onSuccess(String userid) {

                LogUtils.log_E("--onSuccess" + userid);
//                    startActivity(new Intent(MainActivity.this, MainActivity.class));
//                    finish();
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                LogUtils.log_E("--onError" + errorCode);
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


}
